<template>
    <div id="contextmenu" @click.prevent ref="contextmenu">
        <template v-for="menu in contextmenu">
            <div
            class="menu"
            :key="menu.name"
            v-if="!menu.hide"
            @click.stop="(event) => onMenuClick(event, menu)"
            >{{ menu.name }}</div>
        </template>
      </div>
</template>
<script>
import html2canvas from 'html2canvas'
export default {
    name: 'contextMenu',
    data () {
        return {
            fileUrl: '',
            linkUrl: '',
            fileName: '',
            contextmenu: [
                // {
                //     name: '查看',
                //     event: 'view'
                // },
                {
                    name: '刷新',
                    event: 'refresh'
                },
                {
                    name: '打印',
                    event: 'print'
                },
                // {
                //     name: '图片另存为',
                //     event: 'saveAs',
                //     hide: true
                // },
                {
                    name: '下载图片',
                    event: 'download',
                    hide: true
                },
                {
                    name: '复制链接',
                    event: 'saveLink',
                    hide: true
                },
                {
                    name: '下载页面',
                    event: 'saveHtml'
                },
                {
                    name: '换主题',
                    event: 'setting'
                }]
        }
    },
    methods: {
        getColor (val) {
            console.log(val, 'color')
        },
        onMenuClick (event, menu) {
            switch (menu.event) {
            case 'refresh':
                window.location.reload()
                break
            case 'print':
                window.print()
                break
            case 'saveAs':
                // 'Saveas'表示打开“文件另存为”对话框命令
                this.saveAs(this.fileUrl)
                break
            case 'download':
                this.downloadIamge(this.fileUrl, this.fileName)
                break
            case 'saveLink':
                this.saveLink(this.linkUrl)
                break
            case 'saveHtml':
                this.exportHtml(document.title + '.html', document.getElementsByTagName('html')[0].outerHTML)
                break
            default:
                break
            }
            this.$emit('on-menu-click', menu.event)
            this.$refs.contextmenu.style.display = 'none'
        },
        fakeClick (obj) {
            var ev = document.createEvent('MouseEvents')
            ev.initMouseEvent(
                'click', true, false, window, 0, 0, 0, 0, 0
                , false, false, false, false, 0, null
            )
            obj.dispatchEvent(ev)
        },
        exportHtml (name, data) {
            var urlObject = window.URL || window.webkitURL || window
            var exportblob = new Blob([data])
            var savelink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
            savelink.href = urlObject.createObjectURL(exportblob)
            savelink.download = name
            this.fakeClick(savelink)
        },
        downloadIamge (imgsrc, name) { // 下载图片地址和图片名
            let image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function (e) {
                let canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                let context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
                let a = document.createElement('a') // 生成一个a元素
                let event = new MouseEvent('click') // 创建一个单击事件
                a.download = name || 'photo_' + new Date().getTime() // 设置图片名称
                a.href = url // 将生成的URL设置为a.href属性
                a.dispatchEvent(event) // 触发a的单击事件
            }
            image.src = imgsrc
        },
        saveLink (target) {
            const input = document.createElement('input')
            input.setAttribute('readonly', 'readonly')
            input.setAttribute('value', target)
            document.body.appendChild(input)
            input.setSelectionRange(0, 9999)
            if (document.execCommand('copy')) {
                document.execCommand('copy')
                // console.log('复制成功')
                this.$message.success('复制成功!')
            }
            document.body.removeChild(input)
        }
    },
    mounted () {
        window.addEventListener('contextmenu', (e) => {
            // 获取我们自定义的右键菜单
            var menu = this.$refs.contextmenu
            if (menu === null) return

            // 取消默认的浏览器自带右键 很重要！！
            e.preventDefault()
            this.contextmenu.map(el => {
                if (el.event === 'download' ||
                el.event === 'saveAs') {
                    if (e.target.src) {
                        el.hide = false
                        this.fileUrl = e.target.src
                        this.fileName = e.target.title
                    } else {
                        el.hide = true
                    }
                }
                if (el.event === 'saveLink') {
                    if (e.target.href) {
                        el.hide = false
                        this.linkUrl = e.target
                    } else {
                        el.hide = true
                    }
                }
            })
            // 根据事件对象中鼠标点击的位置，进行定位
            menu.style.left = e.pageX + 'px'
            menu.style.top = e.pageY + 'px'

            // 改变自定义菜单的宽，让它显示出来
            menu.style.display = 'block'
        }, true)
        // 关闭右键菜单，很简单
        window.addEventListener('click', (e) => {
            e.preventDefault()
            // 用户触发click事件就可以关闭了，因为绑定在window上，按事件冒泡处理，不会影响菜单的功能
            let contextmenu = this.$refs.contextmenu
            if (contextmenu && contextmenu !== null) {
                contextmenu.style.display = 'none'
            }
        }, false)
    }
}
</script>
<style lang="less" scoped>
#contextmenu {
    position: absolute;
    // height: 160px;
    z-index: 999999999;
    background: @white;
    color: @c-333;
    border-radius: 5px;
    width: 120px;
    display: none;
    overflow: hidden;
    box-shadow: 0 5px 10px @c-333;
    user-select: none;
    .menu {
        padding: 0 10px;
        line-height: 32px;
        font-size: 14px;
        color: @c-333;
        &:hover {
            background: @primary;
            color: @white;
        }
    }
}
</style>
